namespace CIS.UserCheck
{
    using CISLib;
    using System;
    using System.Collections;
    using System.Data;
    using System.IO;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class CheckUserPage : Page
    {
        protected DropDownList AreaDdl;
        protected DropDownList catDdl;
        protected HyperLink InterfaceKPIHk;
        protected Label Label7;
        protected Label lbAreaDdl;
        protected Label lbcatDdl;
        protected Label lbprovinceDdl;
        protected Label lbQuarter;
        protected Label lbRoleDdl;
        protected LinkButton lkbDown;
        protected UserPrincipal Principal = null;
        protected DropDownList provinceDdl;
        protected DropDownList RoleDdl;
        protected Button SearchBtn;
        protected Button startCalculationBtn;
        protected HyperLink teamKPIHk;
        protected DataGrid UserListDg;
        protected DropDownList YQDdl;

        private void AreaDdl_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.provinceDdl.DataSource = ManageProvince.GetProvince(new Guid(this.AreaDdl.SelectedValue));
            this.provinceDdl.DataTextField = "RegionName";
            this.provinceDdl.DataValueField = "RegionId";
            this.provinceDdl.DataBind();
            this.catDdl.DataSource = ManageCAT.GetCAT(new Guid(this.AreaDdl.SelectedValue));
            this.catDdl.DataTextField = "CATGroupName";
            this.catDdl.DataValueField = "CATGroupId";
            this.catDdl.DataBind();
            this.RoleDdl.Items.Clear();
            //Guid tmpGuid = new Guid();
            this.RoleDdl.DataSource = ManageRole.GetRole(new Guid(this.AreaDdl.SelectedValue));
            this.RoleDdl.DataTextField = "RoleName";
            this.RoleDdl.DataValueField = "RoleId";
            this.RoleDdl.DataBind();
            ListItem roleItem = new ListItem("All", "All");
            this.RoleDdl.Items.Insert(0, roleItem);
        }

        private void CalculateUserKPI()
        {
            Guid[] userIdAry = ManageCheckUser.GetUserIdListInCustomerBasicInfo();
            for (int i = 0; i < userIdAry.Length; i++)
            {
                Guid[] customerIdAry = ManageCheckUser.GetCustomerIdListInCustomerBasicInfoViaUserId(userIdAry[i]);
                int updateCount_Inspirit = 0;
                int userCustomerInfoCount = 0;
                for (int j = 0; j < customerIdAry.Length; j++)
                {
                    int emptyCount = 0;
                    CustomerBasicInfo customerBasicInfo = ManageCustomer.GetCustomerBasicInfoViaId(customerIdAry[j]);
                    emptyCount = (customerBasicInfo.Name == "") ? emptyCount : (emptyCount + 1);
                    emptyCount = (customerBasicInfo.Gender.Trim() == "") ? emptyCount : (emptyCount + 1);
                    emptyCount = (customerBasicInfo.Title == "") ? emptyCount : (emptyCount + 1);
                    emptyCount = (customerBasicInfo.MailAdd == "") ? emptyCount : (emptyCount + 1);
                    emptyCount = (customerBasicInfo.Level == 0) ? emptyCount : (emptyCount + 1);
                    emptyCount = (customerBasicInfo.Depart == "") ? emptyCount : (emptyCount + 1);
                    emptyCount = (customerBasicInfo.CustomerDefId.ToString() == "11111111-1111-1111-1111-111111111111") ? emptyCount : (emptyCount + 1);
                    emptyCount = ManageProduct.IsExitProductInCustomerProductViaId(customerBasicInfo.CustomerId) ? (emptyCount + 1) : emptyCount;
                    if (ManageCustomer.IsExistSameCoustomerPersonalInfo(customerIdAry[j]))
                    {
                        CustomerPersonalInfo customerPersonalInfo = ManageCustomer.GetCustomerPersonalInfoViaId(customerIdAry[j]);
                        emptyCount = (customerPersonalInfo.BirthDate.ToString() == "1800-1-1 0:00:00") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerPersonalInfo.BirthPlace == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerPersonalInfo.FamilyAdd == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerPersonalInfo.RelocationAdd == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerPersonalInfo.Mobile == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerPersonalInfo.Weight == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerPersonalInfo.Height == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerPersonalInfo.SpecicalHobbies == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                    }
                    if (ManageCheckUser.IsExistCustomerPreferenceInfoViaId(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    if (ManageCustomer.IsExistSameCoustomerHealthInfo(customerIdAry[j]))
                    {
                        CustomerHealth customerHealth = ManageCustomer.GetCustomerHealthViaId(customerIdAry[j]);
                        emptyCount = (customerHealth.HealthStatus == 3) ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerHealth.Eyesight == 3) ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerHealth.MajorOperation == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerHealth.SpecialDisease == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerHealth.Allergy == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                    }
                    if (ManageCustomer.IsExistSameCoustomerCostumeInfo(customerIdAry[j]))
                    {
                        CustomerCostumeInfo customerCostumeInfo = ManageCustomer.GetCustomerCostumeInfoViaId(customerIdAry[j]);
                        emptyCount = (customerCostumeInfo.BrandPre == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerCostumeInfo.HipMeasurement == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerCostumeInfo.NeckMeasurement == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                        emptyCount = (customerCostumeInfo.ShoesSize == "\0\0\0\0") ? emptyCount : (emptyCount + 1);
                    }
                    if (ManageCustomer.IsExistSameCustomerStudyExperienceInfo(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    if (ManageCustomer.IsExistSameCustomerWorkExperienceInfo(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    if (ManageCustomer.IsExistSameCustomerASBContractInfo(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    if (ManageCustomer.IsExistSameCustomerEVMeetingInfo(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    if (ManageCustomer.IsExistSameCustomerVisitingAbroadInfo(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    if (ManageCustomer.IsExistSameCustomerASBEventsInfo(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    if (ManageCustomer.IsExistSameCustomerEventsInfo(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    if (ManageCustomer.IsExistSameCustomerResponsibleStaffInfo(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    if (ManageCustomer.IsExistSameCustomerASBReceptionInfo(customerIdAry[j]))
                    {
                        emptyCount++;
                    }
                    userCustomerInfoCount += emptyCount;
                    updateCount_Inspirit += this.GetCustomerUpdateNum(customerIdAry[j], userIdAry[i]);
                }
                int userImportCustomerNumCount = 0;
                int userImportCustomerNumAllCount = 0;
                int userCustomerNumAllCount = 0;
                ArrayList companyIdAry = new ArrayList();
                if (customerIdAry.Length > 0)
                {
                    for (int x = 0; x < customerIdAry.Length; x++)
                    {
                        int isExist = 0;
                        Guid tmpId = new Guid();
                        tmpId = ManageCheckUser.GetCompanyIdViaCustomerId(customerIdAry[x]);
                        for (int y = 0; y < companyIdAry.Count; y++)
                        {
                            if (((Guid) companyIdAry[y]) == tmpId)
                            {
                                isExist = 1;
                            }
                        }
                        if (isExist == 0)
                        {
                            companyIdAry.Add(tmpId);
                        }
                    }
                    for (int z = 0; z < customerIdAry.Length; z++)
                    {
                        for (int w = 0; w < companyIdAry.Count; w++)
                        {
                            if (ManageCheckUser.IsExistImportCustomerInKPI((Guid) companyIdAry[w], ManageCheckUser.GetCustomerNameViaCustomerId(customerIdAry[z])))
                            {
                                userImportCustomerNumCount++;
                            }
                        }
                    }
                }
                for (int v = 0; v < companyIdAry.Count; v++)
                {
                    int tmpImportCustomerNumAllCount = ManageCheckUser.GetImportCustomerCountViaIdInOrgTree((Guid) companyIdAry[v]);
                    userImportCustomerNumAllCount += tmpImportCustomerNumAllCount;
                }
                userCustomerNumAllCount = ManageCheckUser.GetCustomerCountViaIdInCustomerBasicInfo(userIdAry[i]);
                double fillInInfoCount = 0.0;
                double updateCount = 0.0;
                if (customerIdAry.Length > 0)
                {
                    fillInInfoCount = Math.Round(Convert.ToDouble(userCustomerInfoCount), 2);
                    updateCount = Math.Round(Convert.ToDouble(updateCount_Inspirit), 2);
                }
                ManageCheckUser.UpdateUserKPI(userIdAry[i], this.YQDdl.SelectedItem.Text, fillInInfoCount, userImportCustomerNumCount, userImportCustomerNumAllCount, userCustomerNumAllCount, updateCount);
            }
        }

        private void CopyUserIdToKPI()
        {
            string selectYQ = this.YQDdl.SelectedItem.Text;
            ManageCheckUser.RemoveUserIdInKPI(selectYQ);
            ManageCheckUser.CopyUserIdToKPI(selectYQ);
        }

        protected string GetAllInfoCount(object obj)
        {
            try
            {
                int tmp = 0;
                tmp = (int) obj;
                tmp *= 0x23;
                return tmp.ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }

        private int GetCustomerUpdateNum(Guid customerId, Guid userId)
        {
            string selectYQ = this.YQDdl.SelectedItem.Text;
            string strYear = selectYQ.Substring(0, 2);
            string strQ = selectYQ.Substring(3, 1);
            return ManageCheckUser.GetCustomerUpdateNumInLog(customerId, strYear, strQ, userId);
        }

        protected string GetUserLogName(object userId)
        {
            return ManageUser.GetUserViaId((Guid) userId).LoginName;
        }

        private void InitializeComponent()
        {
            this.startCalculationBtn.Click += new EventHandler(this.startCalculationBtn_Click);
            this.AreaDdl.SelectedIndexChanged += new EventHandler(this.AreaDdl_SelectedIndexChanged);
            this.SearchBtn.Click += new EventHandler(this.SearchBtn_Click);
            this.lkbDown.Click += new EventHandler(this.lkbDown_Click);
            this.UserListDg.PageIndexChanged += new DataGridPageChangedEventHandler(this.UserListDg_PageIndexChanged);
            base.Load += new EventHandler(this.Page_Load);
        }

        private void InitPage()
        {
            this.teamKPIHk.NavigateUrl = "CheckUserCountTeamPage.aspx";
            this.InterfaceKPIHk.NavigateUrl = "CheckUserPageInterFace.aspx";
            this.AreaDdl.Items.Clear();
            Area[] area = ManageArea.GetAreaAryViaId(this.Principal.SysUser.UserId);
            for (int i = 0; i < area.Length; i++)
            {
                ListItem tmpListItem = new ListItem();
                tmpListItem.Text = area[i].AreaName;
                tmpListItem.Value = area[i].AreaId.ToString();
                this.AreaDdl.Items.Add(tmpListItem);
            }
            this.provinceDdl.DataSource = ManageProvince.GetProvince(new Guid(this.AreaDdl.SelectedValue));
            this.provinceDdl.DataTextField = "RegionName";
            this.provinceDdl.DataValueField = "RegionId";
            this.provinceDdl.DataBind();
            this.catDdl.DataSource = ManageCAT.GetCAT(new Guid(this.AreaDdl.SelectedValue));
            this.catDdl.DataTextField = "CATGroupName";
            this.catDdl.DataValueField = "CATGroupId";
            this.catDdl.DataBind();
            this.RoleDdl.Items.Clear();
            Guid tmpGuid = new Guid();
            this.RoleDdl.DataSource = ManageRole.GetRole(new Guid(this.AreaDdl.SelectedValue));
            this.RoleDdl.DataTextField = "RoleName";
            this.RoleDdl.DataValueField = "RoleId";
            this.RoleDdl.DataBind();
            ListItem roleItem = new ListItem("All", "All");
            this.RoleDdl.Items.Insert(0, roleItem);
        }

        private void lkbDown_Click(object sender, EventArgs e)
        {
            DataTable dt = ManageCheckUser.GetUser(new Guid(this.AreaDdl.SelectedValue), this.provinceDdl.SelectedValue, this.catDdl.SelectedValue, this.RoleDdl.SelectedValue, this.YQDdl.SelectedItem.Text).Tables[0];
            StringWriter sw = new StringWriter();
            for (int ii = 0; ii < dt.Columns.Count; ii++)
            {
                if (ii == (dt.Columns.Count - 1))
                {
                    sw.Write(dt.Columns[ii].ColumnName + "\n");
                }
                else
                {
                    sw.Write(dt.Columns[ii].ColumnName + ",");
                }
            }
            for (int ii = 0; ii < dt.Rows.Count; ii++)
            {
                DataRow dr = dt.Rows[ii];
                for (int jj = 0; jj < dt.Columns.Count; jj++)
                {
                    if (jj == (dt.Columns.Count - 1))
                    {
                        sw.Write(dr[dt.Columns[jj].ColumnName] + "\n");
                    }
                    else
                    {
                        sw.Write(dr[dt.Columns[jj].ColumnName] + ",");
                    }
                }
            }
            sw.Close();
            base.Response.AddHeader("Content-Disposition", "attachment; filename=CustomerInfo" + DateTime.Now.Millisecond.ToString() + ".csv");
            base.Response.ContentType = "application/ms-excel";
            base.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
            base.Response.Write(sw);
            base.Response.End();
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
            this.Principal = this.Context.User as UserPrincipal;
        }

        private void Page_Load(object sender, EventArgs e)
        {
            if (this.Principal.SysUser.IsAdmin == 0)
            {
                throw new ApplicationException(string.Format("User: {0} not has privilege to access this page.", this.Principal.SysUser.LoginName));
            }
            if (!base.IsPostBack)
            {
                this.UserListDg.PageSize = 14;
                this.YQDdl.DataSource = KPIHelper.BuildLastFourYearQuarters(4);
                this.YQDdl.DataBind();
                this.SetFrom();
                this.InitPage();
                this.SetFromImage();
            }
        }

        private void SearchBtn_Click(object sender, EventArgs e)
        {
            this.UserListDgDataBind();
        }

        private void SetFrom()
        {
            string language = this.Session["language"].ToString();
            string path = base.Server.MapPath("~/CIS/LanguageConfig.xml");
            this.lbAreaDdl.Text = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "lbAreaDdl", language, path);
            this.lbcatDdl.Text = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "lbcatDdl", language, path);
            this.lbprovinceDdl.Text = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "lbprovinceDdl", language, path);
            this.lbRoleDdl.Text = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "lbRoleDdl", language, path);
            this.lbQuarter.Text = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "lbQuarter", language, path);
            this.UserListDg.Columns[0].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "Name", language, path);
            this.UserListDg.Columns[1].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "FillInInfoCount", language, path);
            this.UserListDg.Columns[2].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "InfoCount", language, path);
            this.UserListDg.Columns[3].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "FillInImportCustomer", language, path);
            this.UserListDg.Columns[4].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "FillInImportCustomerCount", language, path);
            this.UserListDg.Columns[5].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "AllCustomerCount", language, path);
            this.UserListDg.Columns[6].HeaderText = ManageSystemConfig.GetSystemSetLanguage("CheckUserPage", "UpdateCount_Inspirit", language, path);
        }

        private void SetFromImage()
        {
        }

        private void startCalculationBtn_Click(object sender, EventArgs e)
        {
            this.CopyUserIdToKPI();
            this.CalculateUserKPI();
        }

        private void UserListDg_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            this.UserListDg.CurrentPageIndex = e.NewPageIndex;
            this.UserListDgDataBind();
        }

        private void UserListDgDataBind()
        {
            this.UserListDg.DataSource = ManageCheckUser.GetUser(new Guid(this.AreaDdl.SelectedValue), this.provinceDdl.SelectedValue, this.catDdl.SelectedValue, this.RoleDdl.SelectedValue, this.YQDdl.SelectedItem.Text);
            this.UserListDg.DataBind();
        }
    }
}

